package com.epam.player.desktop.events.button;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JProgressBar;

import com.epam.player.desktop.logic.SaverMP3;
import com.epam.player.vkapi.model.Song;

public class ButtonDownloadActionEvent implements ActionListener {

	private SaverMP3 saverMP3;
	private JList jList;
	JProgressBar jProgressBar;
	JLabel infoDownloading;
	private JButton buttonDownload;
	static String defoultFolder;

	public ButtonDownloadActionEvent(JList jList, JLabel infoDownloading,
			JProgressBar jProgressBar, JButton buttonDownload) {
		this.jList = jList;
		this.saverMP3 = new SaverMP3();
		this.jProgressBar = jProgressBar;
		this.infoDownloading = infoDownloading;
		this.buttonDownload = buttonDownload;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		int index = jList.getSelectedIndex();
		if (index >= 0) {
			final Song song = (Song) jList.getSelectedValue();
			final String name = song.getAuthor() + "-" + song.getTitle()
					+ ".mp3";
			if (defoultFolder == null || defoultFolder == "") {
				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setFileFilter(new ExtFileFilter("mp3",
						"MP3 Files (*.mp3)"));
				fileChooser.setSelectedFile(new File(name));
				int rc = fileChooser.showSaveDialog(null);
				if (rc == JFileChooser.APPROVE_OPTION) {
					File file = fileChooser.getSelectedFile();
					final String filename = file.getAbsolutePath();
					defoultFolder = filename.substring(0,
							filename.lastIndexOf("\\") + 1);
					downloadSong(song, name, filename);
				}
			} else {
				downloadSong(song, name, defoultFolder + name);
			}
		} else {
			infoDownloading.setText("At first, you must select music!");
		}
	}

	private void downloadSong(final Song song, final String name,
			final String filename) {
		final Timer timer = new Timer();
		buttonDownload.setEnabled(false);
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				infoDownloading.setText("Wait please!");
				if (saverMP3.saveMp3(filename, song, jProgressBar)) {
					timer.cancel();
					buttonDownload.setEnabled(true);
					infoDownloading.setText("Download completed.   " + name);
				} else {
					infoDownloading.setText("Error downloading!   " + name);
				}
			}
		}, 0, 1);
	}
}
